package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.RoleBean;
import com.project.bean.RoleLevelBean;
import com.project.dao.IRoleDao;
import com.project.dao.IRoleLevelDao;
import com.project.service.IRoleService;
import com.project.util.InfoResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author lyl
 * description:
 */
@Service
@Transactional
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private IRoleDao iRoleDao;
    @Autowired
    private IRoleLevelDao iRoleLevelDao;

    @Override
    public Page<RoleBean> showRoleByPage(int pageNo) {
        return iRoleDao.selectPage(new Page<>(pageNo, 3), null);
    }

    @Override
    public RoleBean showRoleById(int roleId) {
        return iRoleDao.showRoleById(roleId);
    }

    @Override
    public InfoResult addRole(String roleName, int[] levels) {
        RoleBean roleBean = new RoleBean();
        roleBean.setRoleName(roleName);
        iRoleDao.insert(roleBean);
        long roleId = iRoleDao.selectOne(new QueryWrapper<RoleBean>().eq("roleName", roleName)).getRoleId();
        int x = 0;
        for (int i = 0; i < levels.length; i++) {
            RoleLevelBean rl = new RoleLevelBean();
            rl.setRoleId(roleId);
            rl.setLevelId(levels[i]);
            iRoleLevelDao.insert(rl);
            x = i;
        }
        return new InfoResult(0, "添加成功，新的角色中包含" + (x + 1) + "条权限");
    }

    @Override
    public InfoResult delRoleById(int roleId) {
        InfoResult re = new InfoResult();
        int y = iRoleDao.deleteById(roleId);
        int x = iRoleLevelDao.delete(new QueryWrapper<RoleLevelBean>().eq("fk_roleId", roleId));
        if (x > 0) {
            re.setCode(0);
            re.setInfo("删除成功,受影响的级别行数为" + x + "条,删除了" + y + "个角色");
        }
        return re;
    }

    @Override
    public InfoResult updateRoleById(int roleId, int[] levels) {
        int x = 0;
        QueryWrapper<RoleLevelBean> wa = new QueryWrapper<>();
        //删除用户当前的权限
        wa.eq("fk_roleId", roleId);
        int y = iRoleLevelDao.delete(wa);
        InfoResult infoResult = new InfoResult();
        for (int i = 0; i < levels.length; i++) {
            RoleLevelBean ro = new RoleLevelBean();
            ro.setRoleId(roleId);
            ro.setLevelId(levels[i]);
            iRoleLevelDao.insert(ro);
            x = i;
        }
        infoResult.setCode(0);
        infoResult.setInfo("新增加" + (x + 1) + "个权限,删除" + y + "个旧权限");
        return infoResult;
    }

    @Override
    public List<RoleBean> showAll() {
        return iRoleDao.showAll();
    }
}
